# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
require(gbm)
library(caret)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)

fileName <- "../../03/true_boruta_after.txt"

if (!file.exists(fileName)) {
  quit(status = 0)
}

diffNames <- read_tsv(fileName) %>%
  .$Metabolite

data <- read.csv(opt$i, header = T) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  filter(Metabolite %in% diffNames) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  as.data.frame() %>%
  column_to_rownames("SampleID")

x <- data %>% select(-c("ClassNote"))
y <- data$ClassNote

data
str(data)

rfRs <- randomForest(x, y, importance = T, proximity = TRUE, ntree = 500, mtry = 7)
rfRs

predData <- predict(rfRs, x)
prob <- predict(rfRs, x, type = "prob")

predDf1 <- prob %>%
  as.data.frame(check.names = F, stringsAsFactors = F) %>%
  rownames_to_column("SampleID") %>%
  rowwise() %>%
  do({
       result <- as.data.frame(.)
       values <- result[1,] %>%
         select(-c("SampleID")) %>%
         unlist()
       result$Value <- values[1]
       result
     }) %>%
  select(c("SampleID", "Value")) %>%
  add_column(Prediction = predData)
predictFinalDf1 <- sampleInfo %>%
  left_join(predDf1, by = c("SampleID"))
write_tsv(predictFinalDf1, "Classification_Result.txt")

predDf <- prob %>%
  as.data.frame(check.names = F, stringsAsFactors = F) %>%
  rownames_to_column("SampleID") %>%
  rowwise() %>%
  do({
       result <- as.data.frame(.)
       values <- result[1,] %>%
         select(-c("SampleID")) %>%
         unlist()
       result$Probability <- max(values)
       result
     }) %>%
  select(c("SampleID", "Probability")) %>%
  add_column(Prediction = predData)
predictFinalDf <- sampleInfo %>%
  left_join(predDf, by = c("SampleID")) %>%
  rename(Sample = SampleID) %>%
  select(-c("Probability"), "Probability")
write.csv(predictFinalDf, "RF_Prediction.csv", row.names = F)

varImp <- rfRs$importance
varImpDf <- varImp %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  select(c("Metabolite", "MeanDecreaseAccuracy")) %>%
  rename(VarImp = MeanDecreaseAccuracy) %>%
  arrange(desc(VarImp))
write.csv(varImpDf, "RF_VarImp.csv", row.names = F)

pre_summary = table(predictFinalDf$ClassNote, predictFinalDf$Prediction)

print(pre_summary)
print(pre_summary %>% as.data.frame())
summaryTb <- pre_summary %>%
  as.data.frame() %>%
  as_tibble() %>%
  rename(Var1 = 1, Var2 = 2) %>%
  spread(Var2, "Freq")
print("=log=")
print(summaryTb)
summaryMatrix <- summaryTb %>%
  select(-"Var1") %>%
  as.matrix()
diagSum <- sum(diag(summaryMatrix))
sum <- sum(summaryMatrix)
predictive <- (diagSum / sum) %>%
  round(3)
finalSummaryTb <- summaryTb %>%
  mutate(`Model predictive accuracy` = c(predictive, "")) %>%
  rename(` ` = Var1)
print(finalSummaryTb)

write_csv(finalSummaryTb, "RF_Prediction_Summary.csv")

# cTab = table(predictFinalDf$ClassNote, predictFinalDf$Prediction)
# odd_ratio = (cTab[1, 1] / cTab[1, 2]) / (cTab[2, 1] / cTab[2, 2])
# write.csv(odd_ratio, "Odd_Ratio.csv", row.names = F)

# train.control <- trainControl(method = "cv", number = 10, allowParallel = F)
# # rfRs <- randomForest(x, y, importance = T, proximity = TRUE, ntree = 500, mtry = 7)
# tryCatch(model <<- train(x = x, y = y, importance = T, proximity = TRUE, ntree = 500, mtry = 7,
# trControl = train.control, method = "rf"),
# error = function(e) {
#     model <<- data.frame()
# })
# model
# write.csv(model$results, "model_cv.csv", row.names = F)










